﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using wt.wine.Application.Common.Interfaces;
using wt.wine.Application.Common.Models;
using wt.wine.Application.ManageDevicerecordtalbe;
using wt.wine.Domain.Entities;

namespace wt.wine.Infrastructure.Persistence.Repository
{
    public class DevicerecordRepository : IDevicerecordRepository
    {
        private readonly IApplicationDbContext _dbcontext;
        public DevicerecordRepository(IApplicationDbContext dbcontext)
        {
            _dbcontext = dbcontext;
        }

        /// <summary>
        /// 新增出酒
        /// </summary>
        /// <param name="model"></param>
        /// <param name="cancellationtoken"></param>
        /// <returns></returns>
        public async Task AddDevicerecord(devicerecordtalbe model, CancellationToken cancellationtoken)
        {
            await _dbcontext.devicerecordtalbe.AddAsync(model, cancellationtoken);
            await _dbcontext.SaveChangesAsync(cancellationtoken);
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="skuname"></param>
        /// <param name="dt_begin"></param>
        /// <param name="dt_end"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="cancellationtoken"></param>
        /// <returns></returns>
        public async Task<PaginatedList<GetDevicerecordListDTO>> GetDevicerecoreList(int userid, string skuname, DateTime dt_begin, DateTime dt_end, int pageIndex, int pageSize, CancellationToken cancellationtoken)
        {
            var query = from d in _dbcontext.devicerecordtalbe.AsNoTracking().Where(p =>
             p.userpid == userid && p.state >= 0 && p.updatetime >= dt_begin && p.updatetime <= dt_end && (string.IsNullOrWhiteSpace(skuname) || (!string.IsNullOrWhiteSpace(skuname) && p.name == skuname)))
                        orderby d.updatetime descending
                        select new GetDevicerecordListDTO()
                        {
                            id = d.id,
                            name = d.name,
                            capacity = d.capacity,
                            cusdeviceid = d.cusdeviceid,
                            deviceidno = d.deviceidno,
                            remark = d.remark,
                            updatetime = d.updatetime
                        };
            return await PaginatedList<GetDevicerecordListDTO>.CreateAsync(query, pageIndex, pageSize, cancellationtoken);
        }
    }
}
